import socket
import os
from selenium import webdriver
import time
import random

chromedriver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver"  #将下载的程序放到application文件夹汇总
os.environ["webdriver.chrome.driver"] = chromedriver
username='2020310219'
usepassword='150017'


def isNetOK(testserver):
    s=socket.socket()
    s.settimeout(3)
    try:
        status=s.connect_ex(testserver)
        if status==0:
            s.close()
            return True
        else:
            return False
    except Exception as e:
        return False

def isNetChainOK(testserver=('www.baidu.com', 443)):
    isOK = isNetOK(testserver)

    return isOK

i=0
while i<715:
    chinanet = isNetChainOK()
    if chinanet is False:
        print("疑似存在网络异常")
        try:
            driver = webdriver.Chrome(chromedriver)  # 模拟打开浏览器
            driver.get("http://login.cup.edu.cn/srun_portal_pc?ac_id=1&theme=cup")  # 打开网址
            driver.maximize_window()
            time.sleep(1 + random.random())
            driver.find_element_by_xpath('//*[@id="username"]').send_keys(username)
            driver.find_element_by_xpath('//*[@id="password"]').send_keys(usepassword)
            time.sleep(1 + random.random())
            driver.find_element_by_xpath('//*[@id="login"]').click()
            time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            print('网络连接恢复中,当前时间%s' %(time1))
        except:
            time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            print('网络修复失败，10min后重试,当前时间%s' %(time1))
            time.sleep(600)
            i=0
    else:
        time1=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print('网络连接正常，2h后再次检查,当前时间%s' %(time1))
        time.sleep(7200)